package com.gopay.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * 开关工具类
 * Created by xuHui on 2017/5/16.
 */
public enum SwitchUtils {
    INSTANCE;

    private static final Logger logger = LoggerFactory.getLogger(SwitchUtils.class);

    private static final String OFF = "off";

    private static final String ON = "on";

    private static final String TRACE_SWITCH_KEY = "traceSwitch";

    private static final String traceSwitch = getProp(TRACE_SWITCH_KEY, ON);

    private static String getProp(String name, String def) {
        ResourceBundle rb = null;
        InputStream is = null;
        try {
            is = SwitchUtils.class.getClassLoader().getResourceAsStream("switch.properties");
            if (is != null) {
                rb = new PropertyResourceBundle(is);
            }
        } catch (Exception e) {
            logger.error("load properties error", e);
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error("close stream error", e);
                }
            }
        }
        if (rb != null && rb.containsKey(name)) {
            return rb.getString(name);
        }
        String str = System.getProperty(name);
        if (str != null) {
            return str;
        }
        str = System.getenv(name);
        if (str != null) {
            return str;
        }
        return def;
    }

    public static boolean traceSwitchOff() {
        return OFF.equals(traceSwitch);
    }
}
